package com.erpanderp.wam.ac.model.service.travel;

import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.Session;
import com.erpanderp.wam.ac.model.entity.travel.Logistics;
import com.erpanderp.wam.util.HibernateUtil;

public class LogisticsDAO {
	
	public Logistics createLogistic(Logistics logistic){
		try{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
		System.out.println("FLUSH MODE: " + session.getFlushMode());
		session.setFlushMode(FlushMode.COMMIT);
		session.save(logistic);
		session.getTransaction().commit();
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		
		return logistic;
		
	}
	
	public List<Logistics> getLogistics()
	{
		List<Logistics> logistics = null;
		
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "from Logistics l ";
			Query query = session.createQuery(queryString);
			query.setCacheable(false);
			logistics = (List<Logistics>) query.list();
			session.getTransaction().commit();
			return logistics;
			
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}		
	}
	
	public List<Logistics> getLogisticsByLogistisType(String logisticsType) {
		List<Logistics> logistics = null;
		try {
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "from Logistics l where l.logisticsFor = :logisticsType";
			Query query = session.createQuery(queryString).setString("logisticsType", logisticsType);
			query.setCacheable(false);
			logistics = (List<Logistics>) query.list();
			System.out.println("LIST SIZE IS======="+logistics.size());
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return logistics;
	}
	
	public Logistics getLogistics(String logistics) {
		
		try {
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "from Logistics l where l.displayName = :logistics";
			Query query = session.createQuery(queryString).setString("logistics", logistics);
			query.setCacheable(false);
			List temp = (List<Logistics>) query.list();
			session.getTransaction().commit();
			
			if(temp !=  null && temp.size() > 0){
				return (Logistics) temp.get(0);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}

}
